<?php

/**
 * Created by PhpStorm.
 * Author: 赵凯
 * Date: 2019/12/9
 * Time: 17:10
 */
namespace api\install\controller;

use api\common\model\RlEtAzdModel;
use api\common\model\RlZsmsUserQueryModel;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use think\Config;
use think\Controller;
use think\facade\Cache;
use think\Request;


class BaseController extends Controller
{
    protected $key = 'rili';
    protected $token;
    protected $user_info;

    public function __construct(Request $request = null)
    {
//        require_once '/simplewind/vendor/firebase/php-jwt/src/JWT.php';

        parent::__construct($request);
        $data = $this->check();
        if($data['code']!=200)return json($data);

    }

    public function check(){
        $jwt = $this->request->header('XX-RlUser-Token');
        if(!$jwt) return json(['code'=>10020,'msg'=>'Token不存在']);
        vendor('firebase.php-jwt.src.JWT');
        $prefix = 'cmf_';
        $field  =   [
            'azd.*',
            'azs.server_name'
        ];
        $join   =   [
            ["{$prefix}rl_et_azs azs", 'azs.server_code = azd.server_code'],
        ];
        $key = config('jwt')['key'];
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $info = RlEtAzdModel:: alias('azd')
                ->where('azd.phone',$arr['uid'])
                ->where('azd.active_flag','<>',0)
                ->join($join)
                ->field($field)
                ->find();
            if(empty($info)) return ['code'=>10020,'info'=>$arr];
            $this->user_info = $info;
            return ['code'=>200,'info'=>$arr];
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return ['code'=>-101,'info'=>$e->getMessage()];
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return ['code'=>-102,'info'=>$e->getMessage()];
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            return ['code'=>-103,'info'=>$e->getMessage()];
        }catch(Exception $e) {  //其他错误
            return ['code'=>-104,'info'=>$e->getMessage()];
        }
    }


}